<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Admin\ShopController;
use App\Http\Controllers\Controller;
use App\Http\Services\ASEService;
use App\Http\Services\MobileMessageService;
use App\Http\Services\OrderService;
use App\Models\Card;
use App\Models\City;
use App\Models\Company;
use App\Models\CompanyCity;
use App\Models\Goods;
use App\Models\Order;
use App\Models\Shop;
use App\Models\ShopTime;
use App\Utils\TianZhenLan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    public function get_orders(Request $request) {
        $userId = $request->input('userId');
        $orders = Order::where('user_id', $userId)->with('shopinfo')->with('goodsinfo')->orderBy('id', 'desc')->get();
        $orders = $orders ?: [];
        $hour48 = 48 * 60 * 60;
        $day180 = 180 * 24 * 60 * 60;
        foreach($orders as $order){
            $order->sn_pass = ASEService::encrypt($order->sn);
            $order->can_update = $order->status == 0 ? false : (strtotime($order->time) - time()) > $hour48;
            $order->can_book = (time() - strtotime($order->created_at)) < $day180;
            $order->outTime = time() > strtotime($order->time) ;
        }
        return self::success($orders);
    }

    public function detail(Request $request) {
        $passSn = $request->input('sn');    // 为什么不用ID，因为ID容易随意更改
        $sn = ASEService::decrypt($passSn);
        $order = Order::where('sn', $sn)
            ->with('companyinfo')
            ->with('goodsinfo')
            ->with('shopinfo')
            ->first();
        $mobile = $order->mobile;
        $order->sn1 = $order->sn;
        $order->sn = $passSn;
        $order->mobile1 = substr($mobile, 0, 3) . '******' . substr($mobile, 9);
        $order->mobile2 = $mobile;
        $order->mobile = '';

        // $hour48 = 48 * 60 * 60;
        // $day180 = 180 * 24 * 60 * 60;
        // $order->can_update = $order->status == 0 ? false : (strtotime($order->time) - time()) > $hour48;
        // $order->can_book = (time() - strtotime($order->created_at)) < $day180;
        $order->outTime = time() > strtotime($order->time) ;
        // 获得城市信息
        $cityInfo = CompanyCity::where('company', $order->company)->where('city_id', $order->city)->first();
        if (!preg_match("/^http/", $order->goodsinfo->detail_img)) {
            $order->goodsinfo->detail_img = url(trim($order->goodsinfo->detail_img, '/'));
        }
        $order->cityinfo = $cityInfo;
        return self::success($order);
    }


    public function cities(Request $request) {

        $company = $request->input('company');
        $cityType= $request->input('cityType');

        $cities = CompanyCity::where('company', $company)->where('type', $cityType)->select('city_id', 'city_name', 'city_letter', 'type')->get();

        return self::success($cities);
    }

    public function shops(Request $request) {
        $company    = $request->input('company');
        $city       = $request->input('city');
        $date       = $request->input('date', date('Y-m-d'));
        $shops      = Shop::where('city', $city)->where('company', $company)->get();
        $shopArr    = [];
        foreach ($shops as $key => $shop) {
            $shop->cityInfo = CompanyCity::where(['company' => $company, 'city_id' => $shop->city])->first();

            if ($company == Company::HMT) {
                $shop->times = self::create_time();
            } else {
                $goods = Goods::find($request->input('goods'));
                $times = TianZhenLan::get_shop_time($shop->shop_code, $goods->gid, $date);
                $shop->times = $times;
            }
            if (count($shop->times) != 0) {
                $shopArr[] = $shop;
            }
        }
        return self::success($shopArr);
    }

    public function shop(Request $request) {
        $id = $request->input('id');
        $shop = Shop::find($id);
        $city = City::find($shop->city);
        $shop->city_name = $city->city_name;
        $shop->province_name = $city->province_name;
        if ($shop->company == Company::HMT) {
            $shop->times = self::create_time();
        } else {
            $goods = Goods::find($request->input('goods'));
            $shop->times = TianZhenLan::get_shop_time($shop->shop_code, $goods->gid, $request->date);
        }

        return self::success($shop);
    }

    private static function create_time() {
        $times = [];
        for ($i=0; $i<20; $i++) {
            $hour = str_pad((int)(8 + ( 30 * $i / 60)), "2", '0', STR_PAD_LEFT);
            $min = str_pad($i * 30 % 60, '2', '0',STR_PAD_RIGHT);
            $times[] = ['time' => $hour . ":".$min , 'valid' => 1];
        }
        return $times;
    }


    /**
     * 兑换或修改预约服务信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_order(Request $request) {
        $sn = $request->input('sn', '');
        $sn = ASEService::decrypt($sn);
        $shop = $request->input('shop');
        $time = $request->input('time', '');
        $note = $request->input('note', '');
        $userName = $request->input('user_name', '');
        $userMobile = $request->input('mobile', '');
        $photoerName = $request->input('photoer_name', '');
        $photoerMobile = $request->input('photoer_mobile', '');



        // $data = $request->only(['sn', 'time', 'shop', 'note', 'mobile', 'user_name', 'photoer_name', 'photoer_mobile']);

        $res = OrderService::submit_to_tzl($sn, $shop, $time, $userName, $userMobile, $photoerName, $photoerMobile, $note);

        if ($res['code'] == 200) {
            return self::success();
        } else {
            return self::fail($res['code'], $res['msg']);
        }

        return self::success($data);

        $oldShop    = $order->shop;
        $oldTime    = $order->time;
        $oldUserName    = $order->photoer_name;
        $oldUserMobile  = $order->photoer_mobile;
        $company        = $order->company;
        if ($data['mobile'] != $order->mobile) {
            return self::fail(203, '您的手机与下单时不一致');
        }

        // 分配卡号
        if (!$order->company_card) {
            $card = Card::get_valid_card($company, $order->city, $order->goods);
            if (!$card) {
                return self::fail(202, '缺少卡券');
            }

            // 修改卡券状态
            $card->use_at = datetime();
            $card->order_id = $order->id;
            $card->save();

            $data['company_card']   = $card->code;
        }

        $data['status']         = Order::STATUS_BOOK_OK;
        $data['confirm_at']     = null;
        $data['update_count']   = $order->update_count + 1;

        // DB::beginTransaction();
        $order->update($data);

        // 第三方 提交|修改 订单
        if ($company == Company::TZL) {
            // 向天真蓝提交订单
            if ($order->update_count == 1) {
                // 新增天真蓝预定

                $res = TianZhenLan::create_order($order->id);
                if (!$res) {
                    // 提交失败，恢复订单原始状态
                    Order::reset($order->id);
                    //Db::rollBack();
                    return self::fail(203, TianZhenLan::$error);
                }
            } else {
                // 修改天真蓝预定
                $res = TianZhenLan::update_order(
                    $order->id,
                    $oldShop, $data['shop'],
                    $oldTime, $data['time'],
                    $oldUserName, $data['photoer_name'],
                    $oldUserMobile, $data['photoer_mobile']
                );
                if (!$res) {
                    return self::fail(203, TianZhenLan::$error);
                }
            }
        }
        //DB::commit();

        // 发短信
        if ($company == Company::HMT) {
            // 海马体 发送预约提交成功短信
            // MobileMessageService::send_book_receive($order->mobile);

            // 通知后台管理员
        } else {
            // 天真蓝 发送预约成功短信
            // MobileMessageService::send_book_success($order->id);
        }

        return self::success($data);
    }

    public function verify_add_order(Request $request) {
        $sn = ASEService::decrypt($request->input('sn'));
        $order = Order::where('sn', $sn)->first();
        if ($order->company == Company::HMT || $order->company_sn) {
            return self::success();
        } else {
            return self::fail(201, '预定失败');
        }
    }



    /**
     * 模拟荣数生成订单
     * @param Request $request
     * @return array
     */
    public function createOrder(Request $request) {

        return (new RongshuController())->order_create($request);
    }

    public function goodsList(Request $request) {
        $company = $request->input('company');
        $goods = Goods::where('company', $company)->get();
        return self::success($goods);
    }

    public function getUser(Request $i) {
        $user   = Order::where('user_id', $i->input('userId'))->select('mobile', 'user_name')->orderBy('id', 'desc')->first();
        $mobile = $user->mobile;
        $user->mobile = substr($mobile, 0, 3) . '******' . substr($mobile, 9);
        return self::success($user);
    }

    /**
     * SIP 通知
     */
    public function sip_notify(Request $request) {
        logger($request->all());
        return $request->all();
    }
}
